import settings
from utils.send_api_util import SendAPiUtil
from utils.assertion_util import AssertionUtil
from utils.logger_util import logger


class SendApiBaseModel:
    """
        测试用例执行工具
    """
    def __init__(self):
        self.send_api_util = SendAPiUtil()
        self.assert_util = AssertionUtil()

    def excute_testcase(self, api_info: dict):

        """ 请求基本信息处理 """
        base_api_info = api_info.get("baseInfo")
        testcase_info_list = api_info.get("testcase")
        
        # api名称
        api_name = base_api_info.get("api_name")
        logger.info(f"api_name: {api_info}")
        # api请求方法
        api_method = base_api_info.get("method")
        logger.info(f"api_name: {api_method}")
        # api请求地址
        api_url = base_api_info.get("url")
        logger.info(f"api_name: {api_url}")

        # 设置请求头参数:需要携带token时配置
        if base_api_info.get("apifoxToken") == "true":
            headers = {"apifoxToken": settings.TOKEN}
            self.send_api_util.session.headers.update(headers)
        logger.info(f"headers: {self.send_api_util.session.headers}")

        """ 发送接口请求 """
        for testcase in testcase_info_list:
            # case名称
            case_name = testcase.pop("case_name")
            print(f"case_name: {case_name}")
            # print(f"更新后tesecase:{testcase}")
            # 断言数据
            validation = testcase.pop("validation")
            # 提取数据获取并处理逻辑
            if testcase.get("extract"):
                extract = testcase.pop("extract")
            
            # 经过上述处理，testcase里面仅剩parmas或data或json等请求参数数据
            for data_type, data_value in testcase.items():
            #     # data_type: 请求参数类型(params, data, json, file)
            #     # data_value: 请求参数值
                response = self.send_api_util.send_api(
                    method=api_method,
                    url=api_url,
                    **testcase
                    )
                print(f"{case_name} - {response.json()}")
                """ 断言接口请求 """
                for assert_data in validation:
                    print(assert_data)
                    for k, v in assert_data.items():
                        print(k, v)
                        if k == "status_code":
                            self.assert_util.assert_status(response, v)
                        elif k == "equal":
                            self.assert_util.assert_eq(response, v)

                



